<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.7.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="在最新版Android Studio（2.1）中，已经可以方便的使用Mockito进行含有android api的单元测试了。因此可以更好的进行敏捷开发与持续集成测试。">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="Android Studio中的单元测试">
<meta property="og:url" content="https://ricky9090.github.io/2016/06/30/android_unit_test/index.html">
<meta property="og:site_name" content="Ricky&#39;s Blog">
<meta property="og:description" content="在最新版Android Studio（2.1）中，已经可以方便的使用Mockito进行含有android api的单元测试了。因此可以更好的进行敏捷开发与持续集成测试。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://img.blog.csdn.net/20160630105746560">
<meta property="og:image" content="http://img.blog.csdn.net/20160630113156778">
<meta property="og:image" content="http://img.blog.csdn.net/20160630113453905">
<meta property="og:updated_time" content="2018-06-11T08:46:43.966Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android Studio中的单元测试">
<meta name="twitter:description" content="在最新版Android Studio（2.1）中，已经可以方便的使用Mockito进行含有android api的单元测试了。因此可以更好的进行敏捷开发与持续集成测试。">
<meta name="twitter:image" content="http://img.blog.csdn.net/20160630105746560">
  <link rel="canonical" href="https://ricky9090.github.io/2016/06/30/android_unit_test/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>Android Studio中的单元测试 | Ricky's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ricky's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">A long way to go.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://ricky9090.github.io/2016/06/30/android_unit_test/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ricky">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ricky's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">Android Studio中的单元测试

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2016-06-30 11:46:53" itemprop="dateCreated datePublished" datetime="2016-06-30T11:46:53+08:00">2016-06-30</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2018-06-11 16:46:43" itemprop="dateModified" datetime="2018-06-11T16:46:43+08:00">2018-06-11</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在最新版Android Studio（2.1）中，已经可以方便的使用Mockito进行含有android api的单元测试了。因此可以更好的进行敏捷开发与持续集成测试。</p>
<a id="more"></a>
<h3 id="创建单元测试"><a href="#创建单元测试" class="headerlink" title="创建单元测试"></a><strong>创建单元测试</strong></h3><p>在Android Studio中新建工程，目录结构如下图显示：<br><img src="http://img.blog.csdn.net/20160630105746560" alt="Android Studio的默认工程结构"><br>其中<br><strong>androidTest</strong>    目录是Instrumentation Test的工程代码<br><strong>main</strong>    即App工程代码<br><strong>test</strong>    就是单元测试工程代码。</p>
<h3 id="编写单元测试"><a href="#编写单元测试" class="headerlink" title="编写单元测试"></a><strong>编写单元测试</strong></h3><p>直接打开ExampleUnitTest，会看到Android Studio自动生成的样例代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * To work on unit tests, switch the Test Artifact in the Build Variants view.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExampleUnitTest</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addition_isCorrect</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        assertEquals(<span class="number">4</span>, <span class="number">2</span> + <span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><br><br>测试了<code>2+2=4</code>的逻辑。</p>
<p>接下来稍作修改，引用Mockito库；添加含有Android api调用的测试。<br>为何使用Mockito库呢？这是因为我们的单元测试是直接在PC上运行的，因此并没有真正的Android运行环境，也就没法真正的调用Android各种API，因此我们需要使用一个假的对象（Mock object）来模拟各种API调用并返回预定义好的结果。Mockito就是用来实现Mock功能的测试框架。</p>
<p>在app的<strong>build.gradle</strong>中添加：<br><figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">dependencies</span> &#123;</span><br><span class="line">    <span class="keyword">compile</span> <span class="keyword">fileTree</span>(dir: <span class="string">'libs'</span>, <span class="keyword">include</span>: [<span class="string">'*.jar'</span>])</span><br><span class="line">    testCompile <span class="string">'junit:junit:4.12'</span></span><br><span class="line">    <span class="keyword">compile</span> <span class="string">'com.android.support:appcompat-v7:23.4.0'</span></span><br><span class="line">    testCompile <span class="string">"org.mockito:mockito-core:1.10.19"</span>    <span class="comment">//添加Mockito库</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>修改ExampleUnitTest：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * To work on unit tests, switch the Test Artifact in the Build Variants view.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExampleUnitTest</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addition_isCorrect</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        assertEquals(<span class="number">5</span>, <span class="number">2</span> + <span class="number">2</span>);    <span class="comment">//更改一个错误值，查看单元测试失败的结果</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 调用WifiManager接口，mock返回Wifi列表数量为9，然后使用断言验证</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mytestmethod</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        WifiManager mockWifiManager = mock(WifiManager.class);</span><br><span class="line"></span><br><span class="line">        List&lt;ScanResult&gt; mockResult = mock(List.class);</span><br><span class="line">        when(mockResult.size()).thenReturn(<span class="number">9</span>);</span><br><span class="line">        when(mockWifiManager.getScanResults()).thenReturn(mockResult);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"mock size: "</span> + mockWifiManager.getScanResults().size());</span><br><span class="line">        assertEquals(<span class="number">9</span>, mockWifiManager.getScanResults().size());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><br></p>
<h3 id="运行单元测试"><a href="#运行单元测试" class="headerlink" title="运行单元测试"></a><strong>运行单元测试</strong></h3><p>接下来就可以运行单元测试查看结果了。<br>在样例的注释说明中写道：</p>
<blockquote>
<p>To work on unit tests, switch the Test Artifact in the Build Variants view.</p>
</blockquote>
<p>但实际在我安装的Android Studio 2.1.2版本中，打开Build Variants面板并没有看到 Test Artifact选项……有可能这个界面与IDE的设置有关。但实际没有关系，有多种方法来运行单元测试：<br><br><br>1.像样例注释说明一样，在Build Variants中设置Test Artifact，并点击运行按钮。<br>2.直接在<strong>单元测试类</strong>、或<strong>单元测试所在的包</strong>、或者是<strong>所有测试包的上级java文件夹</strong>上点击鼠标右键，选择菜单中的<strong>Run</strong>项，就会运行单元测试了。<br>以上两种方法运行过程会在Android Studio的Run面板图形化显示测试结果：<br><img src="http://img.blog.csdn.net/20160630113156778" alt="Android Studio的单元测试面板"></p>
<p>此外还可以通过gradle命令来运行单元测试。使用gradle可以通过Android Studio界面操作，也可以直接通过命令行操作：<br>1.通过界面：点击Android Studio右上方的Gradle面板，在Gradle projects所列出的所有Task中，双击测试Task，如<strong>testDebugUnitTest</strong><br><img src="http://img.blog.csdn.net/20160630113453905" alt="Gradle Task界面"><br><br><br>2.命令行进入工程所在文件夹，运行gradle命令：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gradle.bat testDebugUnitTest</span><br></pre></td></tr></table></figure></p>
<p>通过Gradle运行不会在面板中显示图形化的测试进度及结果，会在命令行中输出测试状态：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">com.example.mockitotest.ExampleUnitTest &gt; addition_isCorrect FAILED</span><br><span class="line">    java.lang.AssertionError at ExampleUnitTest.java:20</span><br><span class="line"></span><br><span class="line">2 tests completed, 1 failed</span><br><span class="line"></span><br><span class="line">:app:testDebugUnitTest FAILED</span><br><span class="line"></span><br><span class="line">FAILURE: Build failed with an exception.</span><br><span class="line"></span><br><span class="line">* What went wrong:</span><br><span class="line">Execution failed for task &apos;:app:testDebugUnitTest&apos;.</span><br><span class="line">&gt; There were failing tests. See the report at: file:///D:/work/studio/MockitoTest/app/build/reports/tests/debug/index.html</span><br><span class="line"></span><br><span class="line">* Try:</span><br><span class="line">Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.</span><br><span class="line"></span><br><span class="line">BUILD FAILED</span><br><span class="line"></span><br><span class="line">Total time: 19.162 secs</span><br></pre></td></tr></table></figure></p>
<p><br><br>测试完毕后，除了运行时产生报告，还会自动在工程目录下生成网页形式的Junit测试报告，路径位于：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">app/build/reports/tests</span><br></pre></td></tr></table></figure></p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/android/" rel="tag"># android</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2016/06/28/ontouchlistener_note/" rel="next" title="onTouchListener中的onTouch函数">
                  <i class="fa fa-chevron-left"></i> onTouchListener中的onTouch函数
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2016/07/04/android_output_jar/" rel="prev" title="Android Studio导出jar包">
                  Android Studio导出jar包 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建单元测试"><span class="nav-number">1.</span> <span class="nav-text">创建单元测试</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写单元测试"><span class="nav-number">2.</span> <span class="nav-text">编写单元测试</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行单元测试"><span class="nav-number">3.</span> <span class="nav-text">运行单元测试</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Ricky</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/ricky9090" title="GitHub &rarr; https://github.com/ricky9090" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ricky</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.7.1</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  

</body>
</html>
